#!/bin/bash

# ================================================================
# 首页 API 测试脚本
# 用途：测试首页所有 API 接口的可用性
# 使用：bash 测试首页API.sh
# ================================================================

BASE_URL="http://localhost:8081"
API_PREFIX="/api/front"
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo "================================================================"
echo "               首页 API 接口测试工具"
echo "================================================================"
echo ""
echo "后端地址: $BASE_URL"
echo "测试时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo ""
echo "----------------------------------------------------------------"

# 测试计数器
total_tests=0
passed_tests=0
failed_tests=0

# 测试函数
test_api() {
    local name=$1
    local url=$2
    local method=${3:-GET}
    
    total_tests=$((total_tests + 1))
    
    echo -n "[$total_tests] 测试: $name ... "
    
    if [ "$method" = "GET" ]; then
        response=$(curl -s -o /dev/null -w "%{http_code}" "$BASE_URL$API_PREFIX$url")
    else
        response=$(curl -s -o /dev/null -w "%{http_code}" -X POST "$BASE_URL$API_PREFIX$url")
    fi
    
    if [ "$response" = "200" ]; then
        echo -e "${GREEN}✅ 通过${NC} (HTTP $response)"
        passed_tests=$((passed_tests + 1))
    else
        echo -e "${RED}❌ 失败${NC} (HTTP $response)"
        failed_tests=$((failed_tests + 1))
    fi
}

# 测试带详细信息的 API
test_api_detail() {
    local name=$1
    local url=$2
    
    total_tests=$((total_tests + 1))
    
    echo ""
    echo "[$total_tests] 测试: $name"
    echo "URL: $BASE_URL$API_PREFIX$url"
    
    response=$(curl -s "$BASE_URL$API_PREFIX$url")
    http_code=$(echo "$response" | jq -r '.code // "无"' 2>/dev/null || echo "无")
    
    if [ "$http_code" = "200" ]; then
        echo -e "状态: ${GREEN}✅ 通过${NC}"
        echo "响应码: $http_code"
        
        # 尝试提取数据量
        data_count=$(echo "$response" | jq '.data | length // .data.total // 0' 2>/dev/null || echo "0")
        if [ "$data_count" != "0" ]; then
            echo "数据量: $data_count"
        fi
        
        passed_tests=$((passed_tests + 1))
    else
        echo -e "状态: ${RED}❌ 失败${NC}"
        echo "响应码: $http_code"
        echo "响应内容: $(echo "$response" | head -c 200)"
        failed_tests=$((failed_tests + 1))
    fi
    echo "----------------------------------------------------------------"
}

echo "开始测试..."
echo ""

# ==================== 1. 首页配置相关 ====================
echo "【1. 首页配置相关】"
test_api "首页 Banner" "/pc/home/get/banner"
test_api "首页配置" "/pc/home/get/config"
test_api "热门搜索" "/index/search/keyword"
echo ""

# ==================== 2. 商品相关 ====================
echo "【2. 商品相关】"
test_api_detail "商品列表(热销)" "/product/list?page=1&limit=4&salesOrder=desc"
test_api "商品列表(乡土)" "/product/list?page=1&limit=6"
test_api "商品分类树" "/product/category/get/tree"
test_api "商品筛选条件" "/product/list/before"
test_api "种植基地列表" "/plantation/showList?page=1&limit=20"
echo ""

# ==================== 3. 文章资讯 ====================
echo "【3. 文章资讯相关】"
test_api "热门文章" "/article/hot/list"
test_api "文章分类" "/article/category/list"
# test_api "文章列表(需要分类ID)" "/article/list/1?page=1&limit=5"
echo ""

# ==================== 4. 集市 ====================
echo "【4. 集市相关】"
test_api_detail "集市商品列表" "/mushroom/public/list?page=1&limit=12"
echo ""

# ==================== 5. 工厂收购 ====================
echo "【5. 工厂收购相关】"
test_api_detail "工厂收购列表" "/factory/list?page=1&limit=4"
test_api "工厂价格明细" "/factory/prices?factoryId=1&page=1&limit=10"
echo ""

# ==================== 6. 找货 (可能失败) ====================
echo "【6. 找货相关】"
echo -e "${YELLOW}注意: 此接口可能因数据库表缺失而失败${NC}"
test_api "找货列表" "/sourcing/public/list?page=1&limit=10"
echo ""

# ==================== 7. 用户认证 ====================
echo "【7. 用户认证相关】"
test_api "移动端域名" "/index/get/domain"
# POST 接口需要参数，这里仅测试连通性
# test_api "Token 验证" "/login/token/is/exist" "POST"
echo ""

# ==================== 8. 其他接口 ====================
echo "【8. 其他接口】"
test_api "平台客服" "/index/get/customer/service"
echo ""

# ==================== 测试结果统计 ====================
echo "================================================================"
echo "                      测试结果统计"
echo "================================================================"
echo ""
echo "总测试数: $total_tests"
echo -e "通过数量: ${GREEN}$passed_tests${NC}"
echo -e "失败数量: ${RED}$failed_tests${NC}"

if [ $failed_tests -eq 0 ]; then
    echo -e "\n${GREEN}🎉 所有测试通过！${NC}"
    exit 0
else
    success_rate=$(awk "BEGIN {printf \"%.1f\", ($passed_tests/$total_tests)*100}")
    echo -e "\n${YELLOW}⚠️  成功率: $success_rate%${NC}"
    echo ""
    echo "常见失败原因："
    echo "  1. 后端服务未启动 (端口 8081)"
    echo "  2. 数据库表缺失 (如 eb_sourcing_info)"
    echo "  3. Redis/MySQL 未运行"
    echo ""
    echo "检查命令："
    echo "  lsof -i :8081                      # 检查后端端口"
    echo "  docker ps | grep ryp_scm           # 检查 Docker 容器"
    echo "  curl http://localhost:8081         # 测试后端连通性"
    exit 1
fi

